package com.traffic.api.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayCommerceDataSendRequest;
import com.alipay.api.response.AlipayCommerceDataSendResponse;
import com.google.gson.Gson;
import com.traffic.api.bean.BusArrivedCardTemplate;
import com.traffic.api.bean.Card;
import com.traffic.api.bean.CardFlowBizContent;
import com.traffic.api.entity.CardFlowInfo;
import com.traffic.api.service.CardFlowInfoService;
import com.traffic.api.util.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.traffic.api.util.GlobalUrl.*;

/**
 * Created by churcy on 2017/3/21.
 */
@Controller
@RequestMapping("/cardflow")
public class CardFlowController {
    @Autowired
    private CardFlowInfoService cardFlowInfoService;

    /**
     * 发送card 消息
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/bus/arrived/card", method = RequestMethod.POST)
    public Object sendCardMessage(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> obj = new HashMap<>();
        boolean isException = true;
        String reason = request.getParameter("reason");
        String type = request.getParameter("type");//CREATE UPDATE CANCEL
        String City = request.getParameter("City");
        String BusRouteNo = request.getParameter("BusRouteNo");
        String StartStation = request.getParameter("StartStation");
        String EndStation = request.getParameter("EndStation");
        String CurrentStation = request.getParameter("CurrentStation");
        String ActionName1 = request.getParameter("ActionName1");
        String ActionUrl1 = request.getParameter("ActionUrl1");
        String ActionName2 = request.getParameter("ActionName2");
        String ActionUrl2 = request.getParameter("ActionUrl2");
        String userId = request.getParameter("userId");
        String thirdNo = request.getParameter("thirdNo");
        String lineId = request.getParameter("lineId");
        if (StringUtils.isBlank(ActionUrl1)) {
            ActionUrl1 = ALIPAY_BUS_PAY_QC;
        }
        if (StringUtils.isBlank(ActionUrl2)) {
            ActionUrl2 = LINE_INFO + "?lineId=" + lineId + "&userId=" + userId;
        }
        if (StringUtils.isBlank(ActionName1)) {
            ActionName1 = "扫码乘车";
        }
        if (StringUtils.isBlank(ActionName2)) {
            ActionName2 = "查看最新动态";
        }
        Date now = new Date();
        String nowStr = DateUtils.format2String(now, "yyyy-MM-dd HH:mm:ss.S");
        AlipayClient alipayClient =
                new DefaultAlipayClient(ALIPAY_GATEWAY, SERVER_APP_ID, SERVER_APP_PRIVATE_KEY, "json", UTF_8, SERVER_ALIPAY_PUBLIC_KEY, SIGN_TYPE_RSA);

        AlipayCommerceDataSendRequest commerceRequest = new AlipayCommerceDataSendRequest();

        //初始化 公交到站提心模板消息
        BusArrivedCardTemplate busArrivedCardTemplate = new BusArrivedCardTemplate();
        busArrivedCardTemplate.setCity(City);
        busArrivedCardTemplate.setBusRouteNo(BusRouteNo);
        busArrivedCardTemplate.setStartStation(StartStation);
        busArrivedCardTemplate.setEndStation(EndStation);
        busArrivedCardTemplate.setCurrentStation(CurrentStation);
        busArrivedCardTemplate.setActionName1(ActionName1);
        busArrivedCardTemplate.setActionUrl1(ActionUrl1);
        busArrivedCardTemplate.setActionName2(ActionName2);
        busArrivedCardTemplate.setActionUrl2(ActionUrl2);
        busArrivedCardTemplate.setCreateTime(nowStr);
        //初始化card 信息
        Card<BusArrivedCardTemplate> card = new Card<>();
        card.setCard_template(busArrivedCardTemplate);
        card.setExpire_time(DateUtils.format2String(new Date(now.getTime() + 2 * 60 * 60 * 1000), "yyyy-MM-dd HH:mm:ss.S"));
        card.setGmt_occur(nowStr);
        card.setReason(reason);
        card.setSend_type("SINGLE");
        if (StringUtils.isBlank(thirdNo)) {
            thirdNo = RandomUtil.uuid();
        }
        card.setThird_no(thirdNo);
        card.setType(type);
        //格式化请求参数
        String bizContent = formatCardFlowBizContent(userId, card);
        commerceRequest.setBizContent(bizContent);
        System.out.println(bizContent);
        try {
            do {
                AlipayCommerceDataSendResponse response = alipayClient.execute(commerceRequest);
                result = AlipayUtils.checkAlipayResponse(response);
                obj = (Map<String, Object>) result.get("obj");
                isException = (boolean) result.get("flag");//是否存在异常标记

                if (isException) {
                    break;
                }
                CardFlowInfo cardFlowInfo = new CardFlowInfo();
                cardFlowInfo.setType("1");
                cardFlowInfo.setActionName1(ActionName1);
                cardFlowInfo.setActionName2(ActionName2);
                cardFlowInfo.setActionUrl1(ActionUrl1);
                cardFlowInfo.setActionUrl2(ActionUrl2);
                cardFlowInfo.setBusRouteNo(BusRouteNo);
                cardFlowInfo.setCity(City);
                cardFlowInfo.setCurrentStation(CurrentStation);
                cardFlowInfo.setStartStation(StartStation);
                cardFlowInfo.setEndStation(EndStation);
                cardFlowInfo.setThirdNo(thirdNo);
                cardFlowInfo.setUserId(userId);
                cardFlowInfoService.save(cardFlowInfo);

                obj = BaseResponse.setResponse(null, ResultCodeAndMessage.SUCCESS);
            } while (false);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return obj;
    }

    /**
     * 取消card
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/card/cancel")
    public Object cancelCardFlow(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> obj = new HashMap<>();
        boolean isException;
        String reason = request.getParameter("reason");
        String type = request.getParameter("type");//CREATE UPDATE CANCEL
        String userId = request.getParameter("userId");
        String thirdNo = request.getParameter("thirdNo");
        try {
            do {

            } while (false);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return obj;
    }

    /**
     * 格式化card请求参数
     *
     * @param userId
     * @param card
     * @return
     */

    private String formatCardFlowBizContent(String userId, Card<BusArrivedCardTemplate> card) {
        CardFlowBizContent<BusArrivedCardTemplate> cardFlowBizContent = new CardFlowBizContent<>();
        cardFlowBizContent.setChannel(SERVER_APP_ID);
        cardFlowBizContent.setVersion("1.0");
        cardFlowBizContent.setTarget_id(userId);
        cardFlowBizContent.setTarget_id_type("ALIPAY_USER_ID");
        cardFlowBizContent.setOp_code("public_bus_arrive_notify");
        cardFlowBizContent.setScene_code("bus_service");
        List<Card<BusArrivedCardTemplate>> cardList = new ArrayList<>();
        cardList.add(card);
        Map<String, List<Card<BusArrivedCardTemplate>>> inner = new HashMap<>();
        inner.put("card", cardList);
        cardFlowBizContent.setOp_data(inner);//Map<String, Map<String, List<Card<T>>>> op_data
        Gson gson = new Gson();

        return gson.toJson(cardFlowBizContent);
    }


}
